const Base = require('./base.js');
const {
  think
} = require('thinkjs');
const moment = require('moment');

module.exports = class extends Base {
  async listAction() {
    const page = this.get('page') || 1;
    const size = this.get('size') || 20;
    const model = this.model('user');

    const query = this.get()
    delete query.page
    delete query.size

    if (query.name) {
      query.name = ['like', `%${query.name}%`]
    }

    const data = await model.where(query).order(['id DESC']).page(page, size).countSelect();
    return this.success(data);
  }
  async listAllAction() {
    const model = this.model('user');
    const data = await model.order(['id DESC']).select();
    return this.success(data);
  }

  async putAction() {

    const values = this.post();
    const id = this.post('id');
    const model = this.model('user');

    if (id > 0) {
      await model.where({
        id: id
      }).update(values);

      if(values.end_time){
        await model.where({
          id: id
        }).update({
          is_end: moment(values.end_time).isBefore(moment())? 1:0,
        });
      }
    }

    return this.success(values);
  }

  async updateAction() {
    const id = this.post('id');
    const is_vip = this.post('is_vip');
    const model = this.model('user');
    await model.where({
      id: id
    }).update({
      is_vip: is_vip
    });
    if (is_vip === 1) {
      await model.where({
        id: id
      }).update({
        create_time: ['exp', 'CURRENT_TIMESTAMP()'],
      });
    }
    return this.success();
  }

  async updateStatusAction() {
    const id = this.post('id');
    const status = this.post('status');
    const model = this.model('user');
    await model.where({
      id: id
    }).update({
      status: status
    });
    return this.success();
  }

};